package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mp.listener.VO.IotMsgNotifyData;
import com.zzyl.nursing.mp.listener.VO.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.util.TimeZoneUtils;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-06
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //查询设备是否存在
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId)
                .one();
        if(ObjectUtil.isEmpty(device)){
            log.warn("设备不存在：{}", deviceId);
            return;
        }
        //封装设备数据
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        if (ObjectUtil.isEmpty(services)){
            return;
        }
        services.forEach(service -> {
            LocalDateTime activeTime = TimeZoneUtils.activeTime(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            Map<String, Object> properties = service.getProperties();
            List<DeviceData> list = new ArrayList<>();
            properties.forEach((key, value) -> {
                DeviceData deviceData = new DeviceData();
                BeanUtils.copyProperties(device, deviceData);
                deviceData.setId(null);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(activeTime);
                list.add(deviceData);
            });
            saveBatch(list);

            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(list));
        });
    }

    @Override
    public void deleteDeviceData() {
        LocalDateTime deviceTime = LocalDateTime.now().minusDays(15);
        List<DeviceData> list = lambdaQuery().eq(DeviceData::getAlarmTime, deviceTime).list();
        if (Collections.isEmpty(list)){
            return;
        }
        removeBatchByIds(list);
    }
}
